#!/usr/bin/env python3.10
# -*- encoding: utf-8 -*-
'''
@File    :   crud.py
@Time    :   2024/01/03 19:29:15
@Author  :   windstarry 
@Version :   1.0
'''
# here put the import lib

from django.shortcuts import get_object_or_404
from .auth import get_user_info_from_token,data_permission,BaseFilters


def create(request, data, model):
    if not isinstance(data, dict):
        try:
            data = data.dict()
        except AttributeError:
            raise TypeError("data必须为dict类型或者有dict方法")
    user_info = get_user_info_from_token(request)
    if user_info is None:
        raise ValueError("Failed to get user info from token")
    # 创建时默认添加创建人、修改者
    data['creator_id'] = user_info['id']
    data['modifier'] = user_info['username']
    query_set = model.objects.create(**data)
    return query_set


def batch_create(request, data, model):
    user_info = get_user_info_from_token(request)
    data_list = []
    for item in data:
        if not isinstance(item, dict):
            item = item.dict()
        # 创建时默认添加创建人、修改者和所属部门
        item['creator_id'] = user_info['id']
        item['modifier'] = user_info['username']
        data_list.append(model(**item))
    query_set = model.objects.bulk_create(data_list)
    return query_set


def delete(id, model):
    instance = get_object_or_404(model, id=id)
    instance.delete()
    pass


def update(request, id, data, model):
    dict_data = data.dict()
    user_info = get_user_info_from_token(request)
    # 修改时默认添加修改者
    dict_data['modifier'] = user_info['username']
    instance = get_object_or_404(model, id=id)
    for attr, value in dict_data.items():
        setattr(instance, attr, value)
    instance.save()
    return instance


def retrieve(request, model, filters: BaseFilters = BaseFilters()):
    filters = data_permission(request, filters)
    if filters is not None:
        # 将filters空字符串转换为None
        for attr, value in filters.__dict__.items():
            if getattr(filters, attr) == '':
                setattr(filters, attr, None)
        query_set = model.objects.filter(**filters.dict(exclude_none=True))
    else:
        query_set = model.objects.all()
    return query_set